package center.wxp.sentinel.service.impl;

import center.wxp.sentinel.service.ProviderService;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class ProviderServiceImpl implements ProviderService {
    static int i = 0;
    /**
     * SentinelResource: // 熔断与降级处理
     * @param name
     */
    @Override
    @SentinelResource(value = "helloAnother", fallback = "defaultFallback")
    public void helloAnother(String name) {
        if (name == null || "bad".equals(name)) {
            System.out.println("异常次数：{}" + i ++);
            throw new RuntimeException("发生异常");
        }
        if ("foo".equals(name)) {
            throw new IllegalStateException("oops");
        }
    }

    //处理限流异常
    public void defaultFallback(String name, Throwable throwable) {
        System.out.println("Go to default fallback");
    }

    // 限流与阻塞处理
    @SentinelResource(value = "doSomeThing", blockHandler = "exceptionHandler")
    @Override
    public void doSomeThing(String str) {
        log.info(str);
    }

    /**
     *入参和饭回参数一致
     * @param str
     * @param ex
     */
    public void exceptionHandler(String str, BlockException ex) {
        log.error("blockHandler：" + str, ex);
    }

    @Override
    @SentinelResource(value = "test", blockHandler = "exceptionHandler")
    public void test() {
        System.out.println("Test");
    }

    public void exceptionHandler(BlockException ex) {
        log.error("blockHandler：", ex);
    }

    public String helloFallback(long s, Throwable ex) {
        // Do some log here.
        ex.printStackTrace();
        return "Oops, error occurred at " + s;
    }
}
